package com.ccteam.fluidmusic.ui.local

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentLocalMusicBinding
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 *
 * @author Xiaoc
 * @since 2021/1/7
 *
 * 本地歌曲详情页面显示
 * 与 [LocalMusicViewModel] 联动
 * 显示本地歌曲总页面，负责管理本地歌曲标签
 */
@AndroidEntryPoint
class LocalMusicFragment : Fragment() {

    private var _binding: FragmentLocalMusicBinding? = null
    private val binding get() = _binding!!

    private var parentIds: List<Pair<String, String>> = mutableListOf()

    private val localMusicViewModel by viewModels<LocalMusicViewModel>()

    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLocalMusicBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        postponeEnterTransition()
        view.doOnPreDraw {
            startPostponedEnterTransition()
        }

        val tabLayoutMediator = TabLayoutMediator(binding.tableLayoutLocalMusicType,
            binding.viewpagerLocalMusic){ tab, position ->
            tab.text = parentIds[position].second
        }

        binding.toolbarAlbumDetail.setOnMenuItemClickListener {
            return@setOnMenuItemClickListener when(it.itemId){
                R.id.toolbar_local_music_refresh ->{
                    localMusicViewModel.subscribeLocalRootId(true)
                    true
                }
                else -> false
            }
        }

        mainActivityViewModel.localRootId.observe(viewLifecycleOwner, { localRootId ->
            localRootId?.let {
                // 由于特殊原因（需等待Service启动完成后再加载内容），需要在Fragment中进行数据订阅
                // 这会导致重复订阅，所以我们在设置parentId时，让它仅在第一次设置时进行RootId的订阅
                // 防止重复订阅，具体看parentId的set方法
                localMusicViewModel.setParentId(it)
            }
        })

        localMusicViewModel.localParentIds.observe(viewLifecycleOwner, {
            if(it.isNotEmpty()) {
                parentIds = it
                if(binding.viewpagerLocalMusic.adapter == null){
                    binding.viewpagerLocalMusic.adapter = LocalMusicPagerAdapter(it,this)
                }
                tabLayoutMediator.attach()
            }
        })
    }


    class LocalMusicPagerAdapter(private val parentIds: List<Pair<String,String>>,
                                 fragment: Fragment): FragmentStateAdapter(fragment){

        override fun getItemCount(): Int = parentIds.size

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> LocalMusicPagerFragment.newInstance(parentIds[position].first)
                1 -> LocalAlbumPagerFragment.newInstance(parentIds[position].first)
                2 -> LocalArtistPagerFragment.newInstance(parentIds[position].first)
                else ->
                    throw IllegalArgumentException("错误的布局参数")
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}